package com.odin.rmsservice.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.odin.rmsservice.entity.User;
import com.odin.rmsservice.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author ice
 * @Date 2018-12-10
 */
@Slf4j
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    /**
     * 分页查询用户信息
     *
     * @param model
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @GetMapping("/list")
    public String userList(Model model,
                           @RequestParam(defaultValue = "1", name = "pageIndex") int pageIndex,
                           @RequestParam(defaultValue = "10", name = "pageSize") int pageSize) {
        IPage<User> iPage = userService.page(new Page<User>(pageIndex, pageSize), null);
        List<User> userList = iPage.getRecords();
        model.addAttribute("users", userList);
        return "user/list";
    }

    /**
     * 前往用户信息页,如果id=null就新建，如果id!=null就编辑
     *
     * @param id    用户id
     * @param model 封装用户信息
     * @return 返回用户信息页
     */
    @GetMapping("/pro")
    public String toEditPage(@RequestParam(name = "id", required = false) Long id, Model model) {
        User user = userService.getUserById(id);
        model.addAttribute("user", user);
        return "user/profile";
    }

    /**
     * 新增用户
     *
     * @param user 用户信息
     * @return 返回用户列表页
     */
    @PostMapping("/pro")
    public String addUser(User user) {

        userService.save(user);
        log.info("success add user ： " + user);
        // redirect：表示重定向一个地址
        // forward：表示转发一个地址
        return "redirect:/user/list";
    }

    /**
     * 修改用户信息
     *
     * @param user 根据id更新用户信息
     * @return 返回用户列表页
     */
    @PutMapping("/pro")
    public String updateUser(@RequestParam("id") Long id, User user) {
        user.setId(id);
        userService.updateById(user);
        System.out.println("update user with userId = " + id + "," + user);
        return "redirect:/user/list";
    }

    /**
     * 删除用户
     *
     * @param id 根据id删除
     * @return 返回用户列表页
     */
    @DeleteMapping("/del")
    public String delUser(@RequestParam("id") Long id) {
        userService.removeById(id);
        log.info("delete user,userId=[" + id + "]");
        return "redirect:/user/list";
    }
}
